/*年轻人，只管向前看，不要管自暴自弃者的话*/
package com.znb.okdown.flutter

import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler


/**
 * create by itz on 2024/1/17 15:58
 * desc :
 **/
class FlutterBridge : IBridge<MethodChannel.Result>, MethodCallHandler {

    companion object {
        val instance = FlutterBridgeHelper.flutterBridge
    }

    object FlutterBridgeHelper {
        val flutterBridge = FlutterBridge()
    }

    private val methodChannels = mutableListOf<MethodChannel>()

    //需要在FlutterCacheManager 创建FlutterEngine时初始化
    fun init(engine: FlutterEngine) {
        //name need to be the same as flutter
        val methodChannel = MethodChannel(engine.dartExecutor, Constants.METHOD_CHANNEL_NAME)
        //set handler
        methodChannel.setMethodCallHandler(this)
        methodChannels.add(methodChannel)
    }

    override fun sendMessage(method: String, arguments: Any) {
        for (methodChannel in methodChannels) {
            methodChannel.invokeMethod(method, arguments)
        }
    }

    override fun sendMessage(method: String, arguments: Any, callback: MethodChannel.Result) {
        for (methodChannel in methodChannels) {
            methodChannel.invokeMethod(method, arguments, callback)
        }
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        val state = PluginState(call.method, call.arguments)
        PluginStateManager.instance.callback.postValue(state)
    }
}